package and.booze.now;

import java.util.Locale;
import java.util.Random;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

//always screen on
//sounds
public class BoozeComputer extends Activity implements OnInitListener {

	private int myProgress = 0;
	private int timeIntervall;
	private float p = (float) 0;
	private int pauseProgress = 0;

	// THREADS
	private volatile Thread runner;
	// private Object threadPauseLock;
	// private boolean threadPaused;
	private boolean threadFinished;

	private SharedPreferences settings;
	private ProgressBar progressBar;
	private Vibrator v;

	private TextView slugs;
	private TextView drink;
	private TextView player;
	private TextView backlog;
	private Button nextRound;
	private CheckBox autostart;

	private boolean autostartOn = true;

	// TTS
	private TextToSpeech mTts;
	private int MY_DATA_CHECK_CODE = 0;

	private BroadcastReceiver mReceiver;
	private final String TAG = "BoozeComputer";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.boozecomputer);

		// loads shared preferences
		settings = getSharedPreferences("BoozePreferences", 0);
		timeIntervall = settings.getInt("time", 180);

		// Loads GUI items
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		slugs = (TextView) findViewById(R.id.lableSlugs);
		drink = (TextView) findViewById(R.id.lableDrink);
		player = (TextView) findViewById(R.id.lablePlayer);
		backlog = (TextView) findViewById(R.id.lableBacklogLists);
		nextRound = (Button) findViewById(R.id.buttonNextRound);
		nextRound.setOnClickListener(NextRoundListener);
		autostart = (CheckBox) findViewById(R.id.checkBoxAutostart);
		autostart.setOnCheckedChangeListener(AutostartListener);
		autostart.setChecked(autostartOn);

		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);

		// starts game
		// threadPauseLock = new Object();
		// threadPaused = false;

		startThread();

		mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				Log.v(TAG, "Screen OFF onReceive()");
				screenOFFHandler.sendEmptyMessageDelayed(0, 2000L);
			}
		};
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == MY_DATA_CHECK_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				// success, create the TTS instance
				mTts = new TextToSpeech(this, this);
			} else {
				// missing data, install it
				Intent installIntent = new Intent();
				installIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		ResumeThread();
		IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
		registerReceiver(mReceiver, filter);
		Log.i(TAG, "broadcast receiver registered!");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
		Log.i(TAG, "broadcast UNregistred!");
		if (runner != null) {
			Thread tmp = runner;
			runner = null;
			tmp.interrupt();
		}
		
	}

	private Handler screenOFFHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			super.handleMessage(msg);
			// do something
			// wake up phone
			Log.i(TAG, "ake up the phone and disable keyguard");
			PowerManager powerManager = (PowerManager) BoozeComputer.this
					.getSystemService(Context.POWER_SERVICE);
			long l = SystemClock.uptimeMillis();
			powerManager.userActivity(l, false);// false will bring the screen
												// back as bright as it was,
												// true - will dim it
		}
	};

	@Override
	protected void onPause() {
		super.onPause();
		PauseThread();
	}

	private void ResumeThread() {
		Log.d("Thread", "resumed!");
		/*
		 * synchronized (threadPauseLock) { threadPaused = false;
		 * threadPauseLock.notifyAll(); }
		 */
	}

	private void PauseThread() {
		Log.d("Thread", "paused!");
		/*
		 * synchronized (threadPauseLock) { threadPaused = true; }
		 */
	}

	@Override
	public void onStop() {
		Log.d("onStop", "1");
		super.onStop();
	}

	private synchronized void startThread() {
		if (runner == null) {
			threadFinished = false;
			runner = new Thread(myThread);
			runner.start();
		}
	}

	private Runnable myThread = new Runnable() {
		@Override
		public void run() {
			while (!threadFinished) {
				try {
					myHandle.sendEmptyMessage(0);
					Log.d("BoozeComputer", "running thread");
					Thread.sleep(1000);
				} catch (Throwable t) {
				}
				/*
				 * synchronized (threadPauseLock) { while (threadPaused) { try {
				 * threadPauseLock.wait(); } catch (InterruptedException e) { }
				 * } }
				 */
			}
		}

		Handler myHandle = new Handler() {

			private String rndDrink;
			private String rndName;
			private int rndSlugs;

			@Override
			public void handleMessage(Message msg) {
				p = (float) myProgress * (float) 100 / (float) timeIntervall;
				if (myProgress > timeIntervall * 0.8
						&& slugs.getText().equals("")) {
					int maxSlugs = settings.getInt("slugs", 0);
					Random rnd = new Random();
					rndSlugs = rnd.nextInt(maxSlugs - 1) + 1;
					slugs.setText(Integer.toString(rndSlugs));
					v.vibrate(500);
				}
				if (myProgress > timeIntervall * 0.9
						&& drink.getText().equals("")) {
					rndDrink = GetRandomDrink();
					drink.setText(rndDrink);
					v.vibrate(500);
				}
				if (myProgress >= timeIntervall && player.getText().equals("")) {
					rndName = GetRandomName();
					player.setText(rndName);
					v.vibrate(500);
					backlog.setText(rndName + ": " + rndDrink + " ("
							+ Integer.toString(rndSlugs) + ")\n"
							+ GetHistory(backlog.getText().toString()));

					String myText1 = rndName + "has to drink " + rndSlugs
							+ " slugs of " + rndDrink;
					mTts.speak(myText1, TextToSpeech.QUEUE_ADD, null);
				}

				progressBar.setProgress(Float.valueOf(p).intValue());

				if (Float.valueOf(p).intValue() >= 100) {
					if (autostartOn) {
						if (pauseProgress <= 10) {
							nextRound.setText(getString(R.string.nextRound)
									+ " (" + (10 - pauseProgress++) + ")");
						} else {
							NextRound();
						}
					} else {
						PauseThread();
					}
				}

				myProgress++;
			}
		};
	};

	private String GetHistory(String lastRounds) {
		String[] tmp = lastRounds.split("\n");
		String returnString = "";
		if (tmp.length >= 4) {
			for (int i = 0; i < 4; i++) {
				returnString += tmp[i] + "\n";
			}
		} else {
			for (int i = 0; i < tmp.length; i++) {
				returnString += tmp[i] + "\n";
			}
		}
		return returnString;
	}

	private OnClickListener NextRoundListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			NextRound();
		}
	};

	private OnCheckedChangeListener AutostartListener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			autostartOn = isChecked;
			if (isChecked == false) {
				nextRound.setText(getString(R.string.nextRound));
				pauseProgress = 0;
			}
		}

	};

	private String GetRandomName() {
		String names = settings.getString("players", "n/a");
		return GetRandomItemFromMultiLineString(names);
	}

	private String GetRandomDrink() {
		String drinks = settings.getString("drinks", "n/a");
		return GetRandomItemFromMultiLineString(drinks);
	}

	private String GetRandomItemFromMultiLineString(String str) {
		String item;
		String[] tmp = str.split("\n");
		Random rnd = new Random();
		item = tmp[rnd.nextInt(tmp.length)];
		return item;
	}

	private void resetCurrentRound() {
		ResumeThread();
		slugs.setText("");
		drink.setText("");
		player.setText("");
		myProgress = 0;
		pauseProgress = 0;
		p = (float) 0;
		nextRound.setText(getString(R.string.nextRound));
	}

	private void NextRound() {
		resetCurrentRound();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mainmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.setting: {
			Intent intent = new Intent();
			intent.setClass(BoozeComputer.this, Settings.class);
			startActivity(intent);
		}
			break;
		}
		return true;
	}

	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {
			Toast.makeText(BoozeComputer.this,
					"Text-To-Speech engine is initialized", Toast.LENGTH_LONG)
					.show();
			mTts.setLanguage(Locale.US);
		} else if (status == TextToSpeech.ERROR) {
			Toast.makeText(BoozeComputer.this,
					"Error occurred while initializing Text-To-Speech engine",
					Toast.LENGTH_LONG).show();
		}

	}
}